package aliyun

import (
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"i-hea/utils/httplib"
	"io/ioutil"
	"os"
)

type ttsReqParam struct {
	AppKey     string `json:"appkey"`
	Text       string `json:"text"`
	Token      string `json:"token"`
	Format     string `json:"format"`
	SampleRate int    `json:"sample_rate"`
	Voice      string `json:"voice"`       // 音色：sijia 思佳 https://help.aliyun.com/document_detail/84435.html
	SpeechRate int    `json:"speech_rate"` //语速
	PitchRate  int    `json:"pitch_rate"`  //语调
}

func TTSRquest(fileName, text, voice string, speech, pitch int) (string, error) {

	url := "https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/tts"
	savePath := gTtsSavePath + fileName
	newReq := ttsReqParam{
		AppKey:     appKey,
		Text:       text,
		Token:      getToken(),
		Format:     "wav",
		SampleRate: 8000,
		Voice:      "sijia",
		PitchRate:  pitch,  //语调：-500 ~ 500
		SpeechRate: speech, //语速：-500（0.5倍）～500（2倍），
	}

	if len(voice) > 0 {
		newReq.Voice = voice
	}

	req, err := json.Marshal(newReq)
	if err != nil {
		logs.Error("参数json格式化错误:%v", err)
		return "", fmt.Errorf("入参错误:%s", err.Error())
	}

	header := make(map[string]string)
	header["X-NLS-Token"] = getToken()

	client := httplib.NewHttpClient()

	response, err := client.Send("POST", url, header, req)
	if err != nil {
		logs.Error("TTS请求[%v] 失败:%v", text, err)
	}

	contentType := response.Header.Get("Content-Type")
	body, _ := ioutil.ReadAll(response.Body)
	if "audio/mpeg" == contentType {
		file, err := os.Create(savePath)
		if err != nil {
			logs.Error("创建TTS 存储文件失败:%v,%v", savePath, err)
			return "", err
		}
		defer file.Close()
		file.Write([]byte(body))
		logs.Debug("[%v] TTS请求转换成功", text)
	} else {
		// ContentType 为 null 或者为 "application/json"
		logs.Error("The HTTP statusCode:%v,错误信息:%v ,token:%v", response.StatusCode, string(body), getToken())
		return "", fmt.Errorf("%s", string(body))
	}

	return savePath, nil
}
